package com.bookstore.filter;

import com.bookstore.data.DataConsts;
import com.bookstore.utils.EncodingHttpServletRequest;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EncodingFilter implements Filter {
    private static String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //1.从 配置文件、注解当中 拿到字符编码的信息
        encoding = filterConfig.getInitParameter("encoding");
        //2.如果在配置文件中没有配置字符编码 就使用默认编码
        if (encoding == null || encoding.isEmpty()) {
            encoding = DataConsts.DEFAULT_CHARSET;
        }
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(request, encoding);
        wrapper.setCharacterEncoding(encoding);
        filterChain.doFilter(wrapper, response);
    }
}
